package com.hanxiaozhang.threadbase1ndedition.no1synchronizedkeyword;

import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈脏读举例〉
 * <p>
 * 模拟银行账号：对业务写方法加锁，对业务读方法不加锁，这样行不行？
 * 容易产生脏读（dirtyRead）手写一个代码
 * <p>
 * getMoney() 去的掉 synchronized 关键字会出现脏读
 *
 * @author hanxinghua
 * @create 2021/11/9
 * @since 1.0.0
 */
public class No2DirtyRead {

    public static class Account {

        private int money;

        public synchronized int getMoney() {
            System.out.println("getMoney method thread name = "
                    + Thread.currentThread().getName() + " money = " + money);
            return money;
        }

        public synchronized void setMoney(int money) {
            // 睡眠1000ms
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.money = money;
            System.out.println("setMoney method thread name = "
                    + Thread.currentThread().getName() + " money = " + money);
        }

    }


    public static void main(String[] args) throws InterruptedException {

        Account account = new Account();

        new Thread(() -> {
            account.setMoney(2);
        }, "THREAD-1").start();
        // 睡眠100ms ，让THREAD-1线程进入Running状态
        TimeUnit.MILLISECONDS.sleep(100);
        account.getMoney();
        // 睡眠1000ms ，让THREAD-1线程结束运行
        TimeUnit.MILLISECONDS.sleep(1000);
        account.getMoney();

    }

}
